import axios from 'axios'
import Vue from 'vue'
import router from '../router';

import qs from 'qs'
import { Toast } from 'mint-ui';

//加密

axios.defaults.timeout = 100000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//multipart/form-data

// axios.defaults.baseURL = api;
axios.interceptors.request.use((config) => {
    if (config.method === 'post') {
        config.data = qs.stringify(config.data)
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

// http response 拦截器
axios.interceptors.response.use(
    response => {
        let msg = response.data.msg;
        if (response.data.msgCode == '007') {
            localStorage.clear();
            sessionStorage.clear();
            router.replace({
                path: '/login',
                query: { redirect: router.currentRoute.fullPath }
            })
        }
        if (response.data.msgCode == '006') {
            router.replace({
                path: '/403',
                query: { redirect: router.currentRoute.fullPath }
            })
        }
        return response;

    },
    error => {
        if (error.response) {
            Toast({
                message: '网络错误',
                position: 'middle',
                duration: 5000
            });
        }
        return Promise.reject(error.response.data)
    });

// 返回一个Promise(发送post请求)
export default {
    //get请求
    get(url, param, token) {
        return new Promise((resolve, reject) => {
            if (token) {
                if (localStorage.getItem('TOKEN')) {
                    param.token = localStorage.getItem('TOKEN')
                } else {
                    param.token = sessionStorage.getItem('TOKEN')
                }
            }
            axios({
                method: 'get',
                url,
                params: param,
            }).then(res => {
                resolve(res.data)
            })
        })
    },
    //post请求
    post(url, param, token) {
        return new Promise((resolve, reject) => {
            if (token) {
                if (localStorage.getItem('TOKEN')) {
                    param.token = localStorage.getItem('TOKEN')
                } else {
                    param.token = sessionStorage.getItem('TOKEN')
                }
            }
            axios({
                method: 'post',
                url,
                data: param,
            }).then(res => {
                resolve(res.data)
            })
        })
    }
}